<template>
	<view class="wrap">
		<view class="search">
			<u-search v-model="query.content" @custom="search" @search="search" height="80" placeholder="请输入消息内容"></u-search>
			<u-dropdown ref="uDropdown" :close-on-click-mask="uDropdown.mask" :activeColor="uDropdown.activeColor" :borderBottom="uDropdown.borderBottom">
				<u-dropdown-item v-model="query.msgType" @change="msgTypeChange"
					:title="uDropdown.msgTypeTitle" :options="uDropdown.msgTypeOptions"></u-dropdown-item>	
				<u-dropdown-item v-model="query.agentId" @change="agentChange"
					:title="uDropdown.agentTitle" :options="uDropdown.agentOptions"></u-dropdown-item>
				<u-dropdown-item v-model="query.status" @change="statusChange"
					:title="uDropdown.statusTitle" :options="uDropdown.statusOptions"></u-dropdown-item>	
			</u-dropdown>
		</view>
		<scroll-view class="scroll-list" scroll-y="true" style="width: 100%; height: 87%; margin-top: 5rpx;margin-bottom: 5rpx;" @scrolltolower="loadMore">
			<view>
				<u-swipe-action v-for="(item, index) in list" :key="item.id" :index="index" 
					:options="dynamicGetSwipeActionOptions(item)" @click="click" 
					@open="open" @close="close" class="uni-list" style="margin-top: 10rpx;margin-bottom: 10rpx;">
					<view @click="toView(item.id)">
						<u-row style="margin: 20rpx;">
						<!-- 	<u-col span="2">
								<font class="fontStyle" :style="{color: getFontColorByValue(item.msgType)}">
									{{ msgTypeTranslate(item.msgType) }}
								</font>
							</u-col> -->
							<u-col span="9" class="ellipsisContent">
								{{ agentTranslate(item.agentId) }}
							</u-col>
							<u-col span="3" style="text-align: right;">
								<text :style="{'border-color': getTextColorByValue(item.status),color: getTextColorByValue(item.status)}">
									{{statusTranslate(item.status)}}
								</text>
							</u-col>
						</u-row>
						<u-row style="margin: 10rpx;color:gray;">
							<u-col span="12" class="ellipsisContent">
								{{contentTranslate(item)}}
							</u-col>
						</u-row>
						<u-row style="margin: 20rpx;color:gray;">
							<u-col span="9">
								{{item.createTime}}
							</u-col>
							<u-col span="3" style="text-align: right;color:gray;">
								<text>
									{{ msgTypeTranslate(item.msgType) }}
								</text>
							</u-col>
						</u-row>
					</view>
				</u-swipe-action>
			</view>
			<view class="loadmore" @click="loadMore">
				<u-loadmore :status="loadStatus"></u-loadmore>
			</view>
		</scroll-view>
		<view v-if="hasPermission('wechatAgentNotice_add')" class="btn-plus" @click="toAdd" >
			<u-icon name="plus-circle-fill" size="90" color="#3d87ff"></u-icon>
		</view>
	</view>
</template>

<script>
import { hasPermission } from '../../../common/auth';
	export default {
		data() {
			return {
				query: {
					current: 1,
					size: 20,
					content: ''
				},
				list: [],
				count: 0,
				loadStatus: 'loadmore',
				arrow: false,
				uDropdown: {
					mask: true,
					borderBottom: false,
					activeColor: '#2979ff',
					agentOptions: [],
					agentTitle: '应用名称',
					msgTypeOptions: [],
					msgTypeTitle: '消息类型',
					statusOptions: [],
					statusTitle: '发送状态'
				}
			}
		},
		computed: {
			agentTranslate: function(){
				return (agentId) => {
					let dictData = this.uDropdown.agentOptions.find(e => e.value == agentId);
					let agentName = '';
					if(dictData){
						agentName = dictData.label;
					}
					return agentName || agentId;
				}
			},
			statusTranslate: function(){
				return (status) => {
					// status转为字符串
					status = status + '';
					let dictData = this.uDropdown.statusOptions.find(e => e.value == status);
					let statusName = '';
					if(dictData){
						statusName = dictData.label;
					}
					return statusName || status;
				}
			},
			msgTypeTranslate: function(){
				return (msgType) => {
					msgType = msgType + '';
					let dictData = this.uDropdown.msgTypeOptions.find(e => e.value == msgType);
					let msgTypeName = '';
					if(dictData){
						msgTypeName = dictData.label;
					}
					return msgTypeName || msgType;
				}
			},
			contentTranslate: function(){
				return (item) => {
					const { msgType,content} = item;
					if(!content){
						return '';
					}
					let content2Parse = JSON.parse(content);
					let realContent = '';
					if(msgType == 'text'){
						realContent = content2Parse.content;
					}else if(msgType == 'image'){
						realContent = '...';
					}else if(msgType == 'file' || msgType == 'voice' || msgType == 'video'){
						realContent = '...';
					}else if(msgType == 'textcard'){
						realContent = realContent.concat('标题：' + content2Parse.title);
						realContent = realContent.concat('描述：' + content2Parse.description);
					}else if(msgType == 'markdown'){
						realContent = '...';
					}else if(msgType == 'news'){
						realContent = realContent.concat('标题：' + content2Parse.title);
						realContent = realContent.concat('描述：' + content2Parse.description);
					}
					return realContent;
				}
			}
		},
		onLoad() {
			this.initAgent();
			this.initMsgType();
			this.initStatus();
			this.loadList();
		},
		onShow() {
			if(uni.getStorageSync("refreshWecahtAgentNoticeList") === true){
				uni.removeStorageSync("refreshWecahtAgentNoticeList");
				this.search();
			}
		},
		methods: {
			initAgent() {
				this.$u.api.wechat.wechatAgent.getAgentAllDict({
					
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option)
					res.data.forEach((item) => {
						optionList.push({
							'label': item.name,
							'value': item.agentId
						});
					})
					this.uDropdown.agentOptions = optionList;
				});
			},
			initMsgType() {
				this.$u.api.dictBizData({
					code: 'wechat_group_message_type'
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option)
					res.data.forEach((item) => {
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.uDropdown.msgTypeOptions = optionList;
				});
			},
			initStatus() {
				this.$u.api.dictBizData({
					code: 'wechat_send_status'
				}).then(res => {
					let optionList = [];
					let option = {
						'label': '全部',
						'value': ''
					}
					optionList.push(option)
					res.data.forEach((item) => {
						optionList.push({
							'label': item.dictValue,
							'value': item.dictKey
						});
					})
					this.uDropdown.statusOptions = optionList;
				});
			},
			agentChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.agentId = index;
				this.uDropdown.agentTitle=(index===''?'应用名称':this.getOptionLabel(this.uDropdown.agentOptions,index));
				this.loadList();
			},
			statusChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.status = index;
				this.uDropdown.statusTitle=(index===''?'发送状态':this.getOptionLabel(this.uDropdown.statusOptions,index));
				this.loadList();
			},
			msgTypeChange(index){
				this.list = [];
				this.query.current = 1;
				this.query.msgType = index;
				this.uDropdown.msgTypeTitle=(index===''?'消息类型':this.getOptionLabel(this.uDropdown.msgTypeOptions,index));
				this.loadList();
			},
			dynamicGetSwipeActionOptions: function(item){
				const { status,createTime } = item;
				let expireDate = new Date(createTime).getTime() + 24 * 60 * 60 * 1000;
				let uSwipeActionOptions = [];
				// 应用消息管理，服务端API只有发送应用消息，所以只有新增，没有修改、删除操作;
				// if (this.hasPermission('wechatAgentNotice_edit') && status === 3) {
				// 	uSwipeActionOptions.push({
				// 		text: '编辑',
				// 		style: {
				// 			backgroundColor: '#079cff'
				// 		},
				// 		action: 'edit'
				// 	});
				// }
				//status~ 0(发送成功)、1(发送失败)、2(已撤回)、3(未发送)
				if (this.hasPermission('wechatAgentNotice_recall') 
					&& status === 0 && expireDate > new Date().getTime()) {
					uSwipeActionOptions.push({
						text: '撤回',
						style: {
							backgroundColor: '#dd524d'
						},
						action: 'recall'
					});
				}
				return uSwipeActionOptions;
			},
			getFontColorByValue: function(msgType) {
				let color = '#606266';
				return color;
			},
			getTextColorByValue: function(status){
				let color = '#606266';
				if(status == '0'){
					//0 发送成功
					color = '#19be6b';
				}else if(status == '1'){
					//1 发送失败
					color = '#fa3534';
				}else if(status == '2'){
					//2 已撤回
					color = '#ff9900';
				}else if(status == '3'){
					//3 未发送
					color = '#606266';
				}
				return color;
			},
			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					this.query.current += 1;
					this.loadList();
				}, 100);
			},
			loadList() {
				let vm = this;
				this.$u.api.wechat.wechatAgentNotice.list(this.query).then(res => {
					if (!res.data || !res.data.records || res.data.records == 0) {
						vm.loadStatus = "nomore";
						return;
					}
					vm.list = vm.list.concat(res.data.records);
					vm.list.forEach((item) => {
						item.show = false;
					})
					vm.count = res.total;
					vm.query.current = res.data.current;
					vm.query.size = res.data.size;
					vm.loadStatus = "loadmore";
				});
			},
			search(value) {
				this.list = [];
				this.query.current = 1;
				this.loadList();
			},
			click(rowIndex, btnIndex) {
				let item = this.list[rowIndex];
				let swipeActionOptions = this.dynamicGetSwipeActionOptions(item);
				let { action } = swipeActionOptions[btnIndex];
				if (action == 'edit') {
					this.navTo('form?id=' + item.id + '&mode=edit');
				} else if (action == 'recall') {
					this.handleRecall(item.id, rowIndex);
				}
			},
			toView(id) {
				if(this.hasPermission('wechatAgentNotice_view')){
					this.navTo('form?id=' + id + '&mode=view');
				}
			},
			toAdd() {
				this.navTo('form?mode=add');
			},
			/**
			 * 打开一个swipeAction的同时，需要自动关闭其他的swipeAction
			 * 
			 * @param {Object} index
			 */
			open(index) {
				this.list[index].show = true;
				//下面这行代码不可少
				this.$set(this.list, index, this.list[index]);
				this.list.map((val, idx) => {
					if (index != idx) {
						this.list[idx].show = false;
					}
				})
			},
			close(index) {
				this.list[index].show = false;
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			handleRecall(id, rowIndex) {
				let self = this;
				uni.showModal({
					title: '提示',
					content: '确定撤回？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							self.$u.api.wechat.wechatAgentNotice.recall({
								"id": id
							}).then(res => {
								if (res.success) {
									self.list[rowIndex].show = false;
									//status: 0(发送成功)、1(发送失败)、2(已撤回)、3(未发送)
									self.list[rowIndex].status = 2;
									//下面这行代码不可少，待跟踪源码
									self.$set(self.list, rowIndex, self.list[rowIndex]);
									self.$u.toast('撤回成功！');
								}
							});
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	@import '../../../common/uni.css';
	
	page {
		background-color: #f5f5f5;
	}

	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top) - var(--window-bottom)); // 视高 - 内容区顶部 - 内容区底部
		width: 100%;
	}
	
	.search{
		height:90px;
		background-color: #ffffff;
		background-size: 450px;
	}
	
	.fontStyle{
		font-weight: bold;
	}
	
	.ellipsisContent {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.textBlock {
		padding: 3rpx;
		border-width: 1px;
		border-style: solid;
	}
</style>